package cn.chenhuanming.chuanzhi.config.secure;

import cn.chenhuanming.chuanzhi.dao.StaffDao;
import cn.chenhuanming.chuanzhi.util.entity.Staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Administrator on 2017-04-28.
 */
@Service
public class UserServiceDetails implements UserDetailsService {

    @Autowired
    StaffDao staffDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Staff staff = staffDao.findByUsername(username);
        if(staff==null)
            throw new UsernameNotFoundException("找不到该帐号");
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        String[] acl = staff.getAcl().split(",");
        for (String authority:acl) {
            authorities.add(new SimpleGrantedAuthority(authority));
        }
        return new User(username,staff.getPassword(),authorities);
    }
}
